<?php	namespace Hdphp\Tool;
class Code
{
	//画布宽
	private $width;
	//画布高
	private $height;
	//画布颜色
	private $color;
	//画布
	private $image;
	//验证码数量
	private $length;
	//验证码大小
	private $size;
	//字体
	private $fontfile;
	//种子
	private $seed;
	/**
	 * 构造方法
	 */	
	public function __construct($width=null,$height=null,$color=null,$length=null,$size=null,$fontfile=null,$seed=null)
	{
		$this->width = is_null($width) ? C("CODE_WIDTH") : $width;
		$this->height = is_null($height) ? 50 : $height;
		$this->color = is_null($color) ? "#ffffff" : $color;
		$this->length = is_null($length) ? C("CODE_LEN") : $length;
		$this->size = is_null($size) ? C("CODE_SIZE") : $size;
		$this->fontfile = is_null($fontfile) ? "Hdphp/Tool/simsun.ttc" : $fontfile;
		$this->seed = is_null($seed) ? "123456789qwertyuioasdfghjklzxcvbnm" : $seed;
	}
	public function show()
	{
		//1.头部
		header('Content-type:image/png');

		//2.创建画布，填充颜色
		$this->createBg();
		//3.写字
		$this->write();
		//4.干扰
		$this->makeTrouble();
		//5.输出
		imagepng($this->image);
		//释放资源
		imagedestroy($this->image);
	}
	/**
	 * 制造麻烦
	 */
	private function makeTrouble()
	{
		//画点
		for($i=0;$i<500;$i++)
		{
			//调色
			$color = imagecolorallocate($this->image, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
			//画点
			imagesetpixel($this->image, mt_rand(0, $this->width), mt_rand(0, $this->height), $color);
		}
		//画线
		for($i=0;$i<10;$i++)
		{
			//调色
			$color = imagecolorallocate($this->image, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
			//画线
			imageline($this->image, mt_rand(0, $this->width), mt_rand(0, $this->height), mt_rand(0, $this->width), mt_rand(0, $this->height), $color);
		}
		
	}
	/**
	 * 写字
	 */
	private function write()
	{
		for($i=0;$i<$this->length;$i++){
			//字体xy坐标
			$x = ($this->width / $this->length) * $i + 5;
			$y = ($this->height + $this->size) / 2;
			//颜色
			$color = imagecolorallocate($this->image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
			//字
			$text = $this->seed[mt_rand(0, strlen($this->seed)-1)];
			//写字
			imagettftext($this->image, $this->size, mt_rand(-45, 45), $x, $y, $color, $this->fontfile, $text);
		}
	}
	/**
	 * 创建画布，填充颜色
	 */
	private function createBg()
	{
		//创建画布
		$image = imagecreatetruecolor($this->width, $this->height);
		//调色
		$color = hexdec($this->color);
		//填充
		imagefill($image, 0, 0, $color);
		//存入到属性
		$this->image = $image;
	}
	
}











